package com.mobile.ado.util;

import java.util.ArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

public abstract class Scheduler {

	private ThreadFactory threadFactory;
	private ScheduledExecutorService timer;

	public Scheduler() {

		threadFactory = new DaemonThreadFactory();
		timer = (ScheduledExecutorService) Executors
				.newSingleThreadScheduledExecutor(threadFactory);
	}

	public void startSchedule(boolean isPeroidic) {

		ArrayList<Runnable> runnables = getTaksRunnable();
		for (int i = 0; i < runnables.size(); i++) {
			ArrayList<Long> delays = getDelay();
			if (isPeroidic) {
				ArrayList<Long> periods = getPeriod();
				timer.scheduleAtFixedRate(runnables.get(i), delays.get(i),
						periods.get(i), TimeUnit.SECONDS);
			} else {
				timer.schedule(runnables.get(i), delays.get(i),
						TimeUnit.SECONDS);
			}
		}

	}

	public void stopSchedule() {
		timer.shutdownNow();
	}

	protected static final class DaemonThreadFactory implements ThreadFactory {

		@Override
		public Thread newThread(Runnable runnable) {

			Thread thread = new Thread(runnable);
			thread.setDaemon(true);
			return thread;
		}

	}

	/**
	 * get the tasks to be executed for each timer schedule.
	 * 
	 * @return
	 */
	public abstract ArrayList<Runnable> getTaksRunnable();

	/**
	 * get delay for each task.
	 * 
	 * @return
	 */
	public abstract ArrayList<Long> getDelay();

	/**
	 * get if it should be executed periodicly for each task
	 * 
	 * @return
	 */
	public abstract ArrayList<Long> getPeriod();
}
